package com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.entity.Resource;
import com.github.pagehelper.PageInfo;
import com.mapper.ResourceMapper;
import com.service.ResourceService;
import com.util.AjaxResult;
import com.vo.ResourceAndPageInfoVO;
import com.vo.ResourceObjectVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 陈忠杰
 * @Date: 2021/06/30/下午6：33
 * @Description:这是关于我的资源的Controller
 */
@RestController
@RequestMapping("resource")
public class ResourceController {

    @Autowired
    ResourceService resourceService;

    @RequestMapping("findBackResource.do")
    public AjaxResult findBackResource(Integer pageNo) {
        AjaxResult ajaxResult = new AjaxResult();
        PageInfo<Resource> resourceByUserIdAndPageNo = resourceService.getResourceByUserIdAndPageNo(1, pageNo);
        ajaxResult.setObj(resourceByUserIdAndPageNo);
        return ajaxResult;
    }

    @RequestMapping("findBackResourceByInfo.do")
    public AjaxResult findBackResourceByInfo(ResourceAndPageInfoVO resourceAndPageInfoVO) {
        PageInfo<Resource> backResourceByInfo = resourceService.findBackResourceByInfo(resourceAndPageInfoVO);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setObj(backResourceByInfo);
        return ajaxResult;
    }

    /**
     * @Description: 在服务器中查询是否有上传文件，无返回0，有返回文件大小（Long）
     * @Param: [resourceObj, session]
     * @return: com.util.AjaxResult
     * @Author: 陈忠杰
     * @Date: 2021/7/1
     */
    @RequestMapping("getUploadFileSize")
    public AjaxResult getUploadFileSize(String resourceObj, HttpSession session) {
        ResourceObjectVO resourceObjectVO = JSON.parseObject(resourceObj, ResourceObjectVO.class);

        String original_name = resourceObjectVO.getOriginal_name();
        System.out.println(resourceObjectVO);
        String realPath = session.getServletContext().getRealPath("/upload/czj/" + original_name);
        System.out.println("getSize"+realPath);
        File file = new File(realPath);
        System.out.println(original_name);
        Long fileSize = file.exists() ? file.length() : 0;
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setMsg("查询资源成功小老弟");
        ajaxResult.setObj(fileSize);
        return ajaxResult;
    }

    /**
     * @Description: 添加resource的方法，包括上传文件和在数据库中添加数据
     * @Param: [resource]
     * @return: void
     * @Author: 陈忠杰
     * @Date: 2021/7/1
     */
    @RequestMapping("addFrontResource.do")
    public AjaxResult addFrontResource(@RequestParam("multiFiles") MultipartFile file, HttpSession session, String filename, Resource resource) throws Exception {
        String realPath = session.getServletContext().getRealPath("/upload/czj");
        File file1 = new File(realPath);
        file1.mkdirs();
        //上传路径
        String path = "/upload/czj" + "/" + filename;
        FileOutputStream out = new FileOutputStream(new File(file1, filename), true);
        out.write(file.getBytes());
        out.flush();
        out.close();
        //判断是不是最后一部分数据，如果是，则调用数据存储的方法为resource数据表添加数据
        if (file.getSize() < 1024 * 1024) {
            String title = resource.getTitle();
            String substring = filename.substring(filename.indexOf(".")+1, filename.length());
            int i = resourceService.addResource(title, path, filename, resource.getFile_size(), substring, resource.getCost_type(), resource.getCost_number(), 1, 1, 0);
            //如果返回时不为0，则添加成功
            if (i != 0) {
                System.out.println("添加成功+++++++++++++++++++++++++++++++++++++++++++++++");
            }
        }
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setMsg("666");
        return ajaxResult;
    }

    /**
     * @Description: 这是修改资源的方法
     * @Param: []
     * @return: void
     * @Author: 陈忠杰
     * @Date: 2021/7/1
     */
    @RequestMapping("modifyFrontResource.do")
    public AjaxResult modifyFrontResource(@RequestParam("multiFiles") MultipartFile file, HttpSession session, String filename, Resource resource ,int id) throws Exception {
        String realPath = session.getServletContext().getRealPath("/upload/czj");
        File file1 = new File(realPath);
        file1.mkdirs();
        System.out.println(file1.isDirectory());
        //上传路径
        String path = "/upload/czj" + "\\" + filename;
        FileOutputStream out = new FileOutputStream(new File(file1, filename), true);
        out.write(file.getBytes());
        out.flush();
        out.close();
        System.out.println(file.getSize()+"文件大小");
        //判断是不是最后一部分数据，如果是，则调用数据存储的方法为resource数据表添加数据
        if (file.getSize() < 1024 * 1024) {

            String title = resource.getTitle();
            String substring = filename.substring(filename.indexOf(".")+1, filename.length());
            int i = resourceService.updResource(title, path, filename, resource.getFile_size(), substring, resource.getCost_type(), resource.getCost_number(), 1, 1, 0,id);
            //如果返回时不为0，则添加成功
            System.out.println("i=" + i);
            if (i != 0) {
                System.out.println("修改成功+++++++++++++++++++++++++++++++++++++++++++++++");
            }
        }
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setMsg("666");
        return ajaxResult;
    }

    @RequestMapping("removeFrontResource.do")
    public AjaxResult removeFrontResource(int id){
        int i = resourceService.delResource(id);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setMsg("删除成功！");
        return ajaxResult;

    }

    @RequestMapping("toggleStatus.do")
    public int toggleStatus(int id,int status){
        int i = resourceService.changeStatus(id, status);
        return i;
    }

    @RequestMapping("play.do")
    public ModelAndView play(Model model,HttpServletResponse response, HttpServletRequest request)throws Exception{
//        request.setCharacterEncoding("utf8");
//        response.setContentType("text/html;charset=utf-8");

        String path = request.getParameter("path");
//        String path1 = new String (path.getBytes("GBK"),"ISO-8859-1");
        String path1 = new String (path.getBytes("iso8859-1"),"UTF-8");
        System.out.println(path1);
        ModelAndView modelAndView = new ModelAndView();
        model.addAttribute("path",path1);

        modelAndView.setViewName("background/back_resourceDetailSet");
        return modelAndView;
    }

    @RequestMapping("down.do")
    public ResponseEntity<byte[]> down(int resourceId,HttpSession session){
        Resource resourceById = resourceService.getResourceById(resourceId);
        String path = resourceById.getPath();
        String realPath = session.getServletContext().getRealPath(path);

        //对下载的文件名重新编码
        //String fileName = new String (file.getName().getBytes("GBK"),"ISO-8859-1");
        String original_name = null;
        try {
            original_name = new String (resourceById.getOriginal_name().getBytes("GBK"),"ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] body=null;

        HttpHeaders httpHeaders = new HttpHeaders();
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(realPath));
            body=new byte[fileInputStream.available()];
            fileInputStream.read(body);
            System.out.println(original_name);
            httpHeaders.setContentDispositionFormData("attachment",original_name);
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ResponseEntity<>(body,httpHeaders, HttpStatus.OK);
    }

}
